<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');

class Friends_mod extends CI_Model
{   
    
    private $_dbTableFriends = 'friends';
    private $_dbTableUsers = 'users';
    private $_dbTableImages = 'images';
    /**
     *  class sonstructor
     */
    function __construct() 
	{
		// Call the Model constructor
        parent::__construct();
	}
    
    public function getMyFriendsList($id, $name=NULL) // $id = my_id
    {
        // SELECT  favorites.id as favorite_id, ( SELECT name FROM images WHERE `private`=0 and `user_id`= favorite_id ORDER BY main desc LIMIT 0,1 ) as image_name, users.username, users.flirt_text  FROM favorites LEFT JOIN users ON favorites.favorite_id = users.id ORDER BY favorite_id        
        $sql = "SELECT {$this->_dbTableFriends}.id,
                       {$this->_dbTableFriends}.user_id,
                       {$this->_dbTableFriends}.friend_id,
                       {$this->_dbTableFriends}.accept,
                       {$this->_dbTableUsers}.username,
                       {$this->_dbTableUsers}.name,
                       {$this->_dbTableUsers}.flirt_text,
                       ( SELECT name  FROM {$this->_dbTableImages} WHERE `private`=0 and `user_id`= friend_id ORDER BY main desc LIMIT 0,1 ) as image_name
                FROM  {$this->_dbTableFriends}, {$this->_dbTableUsers}
                WHERE {$this->_dbTableFriends}.friend_id = {$this->_dbTableUsers}.id
                      AND {$this->_dbTableFriends}.user_id = $id 
                      AND {$this->_dbTableFriends}.accept = 1 ";
        if( $name != "" )
          $sql .= " AND ( {$this->_dbTableUsers}.name LIKE '%{$name}%' OR {$this->_dbTableUsers}.username LIKE '%{$name}%' ) ";
                     
        $sql .= "     ORDER BY {$this->_dbTableFriends}.accept ASC, {$this->_dbTableFriends}.timestamp DESC;
               ";
        $query = $this->db->query($sql);
        
        //echo $this->db->last_query();
        $errors = $this->db->_error_message();
        if (!empty($errors)) {
          throw new Exception("SQL Error: " . $errors);
        } else { }

        if ($query->num_rows() > 0) {
          $result = $query->result();
          $query->free_result();
        } else {
          $result = NULL;
        }

        return $result;
    }
    
    
    public function getMyFriends()
    {
        $id = $this->session->userdata('user_id');
        $sql = "SELECT {$this->_dbTableFriends}.id,
                       {$this->_dbTableFriends}.user_id,
                       {$this->_dbTableFriends}.friend_id,
                       {$this->_dbTableUsers}.username,
                       {$this->_dbTableUsers}.name,                       
                       ( SELECT name  FROM {$this->_dbTableImages} WHERE `private`=0 and `user_id`= friend_id ORDER BY main desc LIMIT 0,1 ) as image_name
                FROM  {$this->_dbTableFriends}, {$this->_dbTableUsers}
                WHERE {$this->_dbTableFriends}.friend_id = {$this->_dbTableUsers}.id
                      AND {$this->_dbTableFriends}.user_id = $id
                      AND {$this->_dbTableFriends}.accept = 1 /* samo koji su prihvatili */
                ORDER BY {$this->_dbTableFriends}.timestamp DESC;
               ";
        $query = $this->db->query($sql);
        
        //echo $this->db->last_query();
        $errors = $this->db->_error_message();
        if (!empty($errors)) {
          throw new Exception("SQL Error: " . $errors);
        } else { }

        if ($query->num_rows() > 0) {
          $result = $query->result();
          $query->free_result();
        } else {
          $result = NULL;
        }

        return $result;
    }
    
    
    public function getMyFriendRequest($id,$name="") // MY ID
    {
      $sql = "SELECT {$this->_dbTableFriends}.id,
                       {$this->_dbTableFriends}.user_id,
                       {$this->_dbTableFriends}.friend_id,
                       {$this->_dbTableFriends}.accept,
                       {$this->_dbTableUsers}.username,
                       {$this->_dbTableUsers}.name,
                       {$this->_dbTableUsers}.flirt_text,
                       ( SELECT name  FROM {$this->_dbTableImages} WHERE `private`=0 and `user_id`= {$this->_dbTableFriends}.user_id ORDER BY main desc LIMIT 0,1 ) as image_name
                FROM  {$this->_dbTableFriends}, {$this->_dbTableUsers}
                WHERE {$this->_dbTableFriends}.user_id = {$this->_dbTableUsers}.id
                      AND {$this->_dbTableFriends}.friend_id = $id 
                      AND {$this->_dbTableFriends}.accept = 0";
        if( $name!="" )
          $sql .= " AND ( {$this->_dbTableUsers}.name LIKE '%{$name}%' OR {$this->_dbTableUsers}.username LIKE '%{$name}%' ) ";
          
        $sql.="       ORDER BY {$this->_dbTableFriends}.accept ASC, {$this->_dbTableFriends}.timestamp DESC;
               ";
        $query = $this->db->query($sql);
        
        //echo $this->db->last_query();
        $errors = $this->db->_error_message();
        if (!empty($errors)) {
          throw new Exception("SQL Error: " . $errors);
        } else { }

        if ($query->num_rows() > 0) {
          $result = $query->result();
          $query->free_result();
        } else {
          $result = NULL;
        }

        return $result;
    }
    
    /**
     * 
     * @return int num friend request
     * @throws Exception
     */
    public function getNumMyFriendRequest()
    {
        $id = $this->session->userdata('user_id');
        $query = $this->db->select('id')
                          ->from($this->_dbTableFriends)
                          ->where('friend_id',$id) // oni koji su meni poslali zahtev
                          ->where('accept',0)
                          ->get();
        
        $errors = $this->db->_error_message();
        if (!empty($errors)) {
          throw new Exception("SQL Error: " . $errors);
        } else { }
        
        $result = $query->num_rows();
       
        return $result;
    }
    
    public function isMyFriend($friend_id)
    {
        $id = $this->session->userdata('user_id');
        $query = $this->db->select('id')
                          ->from($this->_dbTableFriends)
                          ->where('user_id',$id)
                          ->where('friend_id',$friend_id)
                          ->where('accept',1)
                          ->get();
        $errors = $this->db->_error_message();
        if (!empty($errors)) {
          throw new Exception("SQL Error: " . $errors);
        } else { }

        if ($query->num_rows() > 0) {
          $result = true;
          $query->free_result();
        } else {
          $result = false;
        }

        return $result;
    }
    
    /**
     *  AJAX
     */
    public function remove_friend($friend_id)
    {        
        $my_id = $this->session->userdata('user_id');
        $this->db->where('user_id',$my_id);
        $this->db->where('friend_id',$friend_id);
        $this->db->delete($this->_dbTableFriends);
        
        $this->db->where('user_id',$friend_id);
        $this->db->where('friend_id',$my_id);
        $this->db->delete($this->_dbTableFriends);
        
        $errors = $this->db->_error_message();
        if (!empty($errors)) {
          throw new Exception("SQL Error: " . $errors);
        } else { }
        
        return true;
    }
    
    /**
     *  AJAX
     */
    public function add_friend($id)
    {    
        $data = array(
                'accept'=>1
            );  
        //$this->db->where('user_id',$this->session->userdata('user_id'));
        $this->db->where('id',$id);
        $this->db->update($this->_dbTableFriends,$data);
        
        $errors = $this->db->_error_message();
        if (!empty($errors)) {
          throw new Exception("SQL Error: " . $errors);
        } else { }
        
        if( $this->db->affected_rows() == 1 )
        {
           $query = $this->db->select("`user_id`,`friend_id`")
                             ->where('id',$id)
                             ->get($this->_dbTableFriends);
           if( $query->num_rows() == 1 )
           {
             $friend = $query->row();
             $data = array(
                      'user_id'=>$friend->friend_id,
                      'friend_id'=>$friend->user_id,
                      'accept'=>1
                    );
             $this->db->insert($this->_dbTableFriends,$data);             
           }
           $result = true;
        }
        else
           $result = false;
        
         return $result;
    }
    
    
    public function send_friend_request($friend_id)
    {
        $user_id = $this->session->userdata('user_id');
        $sql = "SELECT `id` 
                FROM {$this->_dbTableFriends}
                WHERE (`user_id` = $user_id AND `friend_id` = $friend_id )
                    OR
                      (`user_id` = $friend_id AND `friend_id` = $user_id )
               ;
               ";
//        $query = $this->db->select('id')
//                          ->where('user_id',$this->session->userdata('user_id'))
//                          ->where('friend_id',$id)
//                          ->get($this->_dbTableFriends);
        $query = $this->db->query($sql);
        //echo $this->db->last_query();        
        $errors = $this->db->_error_message();
        if (!empty($errors)) {
          throw new Exception("SQL Error: " . $errors);
        } else { }
        
        if( $query->num_rows() > 0 )
        {
          return -1;
        }
        $query->free_result();
        
        // Placanje ako ima novca
        $query = $this->db->select('coins')
                          ->where('id',$user_id)
                          ->get($this->_dbTableUsers);
        
        $errors = $this->db->_error_message();
        if (!empty($errors)) {
          throw new Exception("SQL Error: " . $errors);
        } else { }
        //echo $this->db->last_query();
        if ($query->num_rows() == 1) {
          $coins = $query->row()->coins;          
          $query->free_result();          
        } else {
          //$coins = 0;
          return 0; 
        }        
        $friend_request_cost = $this->config->item('friend_request_cost');
        //echo $friend_request_cost;
        if( $coins >= $friend_request_cost )
        {
          // Smanji kredit 
          $sql = "UPDATE {$this->_dbTableUsers} SET `coins`=`coins`-{$friend_request_cost} WHERE `id`={$user_id}; ";
          $query = $this->db->query($sql);
          //echo $this->db->last_query();
          $errors = $this->db->_error_message();
          if (!empty($errors)) {
            throw new Exception("SQL Error: " . $errors);
          } else { }
          
          if ($this->db->affected_rows() != 1) {
              return false;
              //$query->free_result();
          } else { }
        }
        else
        {
          //echo "NEma pare";
          return -2; // Nema novcica
        }
        
        
        // Posalji zahtev za prijatteljstvo
        $data = array(
                  'user_id' => $user_id,
                  'friend_id' => $friend_id
              );
        $this->db->insert($this->_dbTableFriends,$data);
        
        $errors = $this->db->_error_message();
        if (!empty($errors)) {
          throw new Exception("SQL Error: " . $errors);
        } else { }
        
        if( $this->db->affected_rows() == 1 )
        {
           // Ako je friend request upucen fake nalogu onda postavi da odma bude prijatelj
           if( false != ($f_id = $this->_isFake($friend_id)) )
               $this->add_friend($f_id);
           
           $result = 1;
        }
        else
           $result = 0;
        
         return $result;
    }
    
    private function _isFake($id)
    {
        $query = $this->db->select("is_fake")
                          ->from($this->_dbTableUsers)
                          ->where('id',$id)
                          ->get();
        $errors = $this->db->_error_message();
        if (!empty($errors)) {
          throw new Exception("SQL Error: " . $errors);
        } else { }
        
        if( $query->num_rows() == 1 )
        {
           $user = $query->row();
           if( 1==$user->is_fake )
            $result = $this->_getFriendReqID($id);
           else
            $result = false;
        }
        else
           $result = false;
        
         return $result;
                
    }
    
    private function _getFriendReqID($friend_id)
    {
        $my_id = $this->session->userdata('user_id');
        $query = $this->db->select('id')
                          ->from($this->_dbTableFriends)
                          ->where('user_id',$my_id)
                          ->where('friend_id',$friend_id)
                          ->get();
        
        if( $query->num_rows() == 1 )
        {
           $row = $query->row();          
           $result = $row->id;          
        }
        else
           $result = false;
        
         return $result;         
    }
    
}// end class Friends_mod

/*
      $query = $this->db->select('*')
                        ->from()
                        ->where()
                        ->get();
      //echo $this->db->last_query();
      $errors = $this->db->_error_message();
      if (!empty($errors)) {
        throw new Exception("SQL Error: " . $errors);
      } else { }

      if ($query->num_rows() > 0) {
        $result = $query->result();
        $query->free_result();
      } else {
        $result = NULL;
      }

      return $result;
 */

// end file: application/models/friends_mod.php

?>